package com.shaoshaohuo.app.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ScrollView;
import android.widget.TextView;

import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.constant.BrandScopeStatus;
import com.shaoshaohuo.app.constant.ExtraName;
import com.shaoshaohuo.app.constant.UMengEventID;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.EcHotSell;
import com.shaoshaohuo.app.entity.EcMainEntity;
import com.shaoshaohuo.app.entity.EcMainEntity.EcMain;
import com.shaoshaohuo.app.entity.FocusImage;
import com.shaoshaohuo.app.entity.MainEntity;
import com.shaoshaohuo.app.entity.UserInfoEntity;
import com.shaoshaohuo.app.entity.brandscope.BrandScope;
import com.shaoshaohuo.app.listener.UserInfoListener;
import com.shaoshaohuo.app.ui.ec.BrandScopeActivity;
import com.shaoshaohuo.app.ui.ec.BrandScopeApplyActivity;
import com.shaoshaohuo.app.utils.StringUtil;
import com.shaoshaohuo.app.utils.im.IMFactory;
import com.shaoshaohuo.app.framework.AccountManager;
import com.shaoshaohuo.app.net.HttpRequest.RequestListener;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.ui.LoginActivity;
import com.shaoshaohuo.app.ui.MainTabActivity;
import com.shaoshaohuo.app.adapter.EcmainGridviewAdapter;
import com.shaoshaohuo.app.ui.ec.BusinessOpportunityActivity;
import com.shaoshaohuo.app.ui.ec.DumpHallActivity;
import com.shaoshaohuo.app.ui.ec.MyFragmentActivity;
import com.shaoshaohuo.app.ui.ec.MyLogisticsActivity;
import com.shaoshaohuo.app.ui.ec.PurchaseHallActivity;
import com.shaoshaohuo.app.ui.ec.SearchActivity;
import com.shaoshaohuo.app.ui.ec.SeasonHotActivity;
import com.shaoshaohuo.app.ui.ec.SupplyHallActivity;
import com.shaoshaohuo.app.entity.AdModel;
import com.shaoshaohuo.app.view.AdViewPager;
import com.shaoshaohuo.app.view.MeasureGridView;
import com.shaoshaohuo.app.view.MessageDialog;
import com.shaoshaohuo.app.view.TopbarView;
import com.shaoshaohuo.app.utils.ToastUtil;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName EcMainActivity
 * @author linmu
 * @Decription 电商首页
 * @2015-8-28 下午9:40:41
 */
public class EcMainFragment extends Fragment implements OnClickListener {
	private View mContentView;

    private TopbarView mTopbarView;
    
    private View mSearchLayout;
    private TextView mSearchEdit;
    
    private View mShangjiLayout;
    private View mGongyingLayout;
    private View mCaigouLayout;
    private View mWuliuLayout;
    private View mServiceContactLayout;
    private View mShuaihuoLayout;
    
//    private MeasureGridView mActionGv;
    private MeasureGridView mSeasonHotGv;
    private MeasureGridView mGongyingHotGv;
    private ScrollView scrollView;

    private AdViewPager adViewPager;
    
    private String mArgument;
    
    public static final String ARGUMENT = "argument";
    
	public static EcMainFragment sharedInstance(String argument)
	{
		Bundle bundle = new Bundle();
		bundle.putString(ARGUMENT, argument);
		EcMainFragment contentFragment = new EcMainFragment();
		contentFragment.setArguments(bundle);
		return contentFragment;
	}
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
		if (bundle != null)
			mArgument = bundle.getString(ARGUMENT);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        if (mContentView == null) {
            mContentView = inflater.inflate(R.layout.activity_ec_main, null);

            initView();
            setUpView();
            requestData();
        } else {
            ViewGroup parent = (ViewGroup) mContentView.getParent();
            if (parent != null) {
                parent.removeView(mContentView);
            }
        }
        return mContentView;
    }
    private void requestData() {
    	RequestService.getInstance().getEcMainIndex(getActivity(), EcMainEntity.class, new RequestListener() {
            
            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {
                if(resultData.isOk()){
                    EcMainEntity entity = (EcMainEntity) resultData; 
                    EcMain data = entity.getData();
                    setHotSell(data.getHotsell());
                    setHotSupply(data.getHotsupply());
//                    setAdViewPager(data.getImages());
//                    adViewPager.setOnClickListener(new OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
//
//                        }
//                    });
                }else{
                    
                }
            }
            
            @Override
            public void onFailed(int requestCode, Exception error, String msg) {
            }
        });
    	RequestService.getInstance().mainIndex(getActivity(), 1 + "", MainEntity.class, new RequestListener() {

            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {

                if (resultData.isOk()) {
                    MainEntity result = (MainEntity) resultData;
                    AccountManager.saveBaoxian(result.getData().getBx());
                    setAdViewPager(result.getData().getFocus());

                } else {
                    ToastUtil.toast(resultData.getMsg());
                }
            }

            @Override
            public void onFailed(int requestCode, Exception error, String msg) {
            }
        });
    }

    private void setAdViewPager(List<FocusImage> images) {
    	List<AdModel> dataList = new ArrayList<AdModel>();
    	for (FocusImage focusImage : images) {
            if("3".equals(focusImage.getPageid()))continue;//如果为 3  是物流图片

    		AdModel aa = new AdModel();
    		aa.setImageUrl(focusImage.getBigimg());
            aa.setLinkUrl(focusImage.getUrl());
            aa.setTitle(focusImage.getTitle());
    		dataList.add(aa);
    	}
    	adViewPager.freshData(dataList);
    	scrollView.smoothScrollTo(0, 0);
    }
    
	protected void setHotSupply(List<EcHotSell> hotsupply) {
        EcmainGridviewAdapter<EcHotSell> adapter = new EcmainGridviewAdapter<>(getActivity(), hotsupply, false);
        mGongyingHotGv.setAdapter(adapter);
    }

    protected void setHotSell(List<EcHotSell> hotsell) {
        EcmainGridviewAdapter<EcHotSell> adapter = new EcmainGridviewAdapter<>(getActivity(), hotsell, false);
        mSeasonHotGv.setAdapter(adapter);
    }

    private void initView() {
        mTopbarView = (TopbarView) mContentView.findViewById(R.id.topbar);
        mTopbarView.setCenterModel(TopbarView.ID_TITLE_INDEX_EC);
        if(getActivity() instanceof MainTabActivity){
        	mTopbarView.setLeftImage(R.drawable.navbar_menu);
        	mTopbarView.setLeftClickListener(new OnClickListener() {
        		
        		@Override
        		public void onClick(View v) {
        			((MainTabActivity) getActivity()).toggle();
        		}
        	});
        }else if(getActivity() instanceof MyFragmentActivity){
        	mTopbarView.setLeftView(true, true);
        	/*
        	mTopbarView.setLeftClickListener(new OnClickListener() {
        		
        		@Override
        		public void onClick(View v) {
        			getActivity().finish();
        		}
        	});*/
        }
        
        if (IMFactory.getUnreadCount() > 0) {
        	mTopbarView.setRightImage(R.drawable.icon_message_unread_ad);
        } else {
        	mTopbarView.setRightImage(R.drawable.icon_message_ad);
        }
        mTopbarView.setRightClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (AccountManager.isLogin()) {
//                    Intent intent = new Intent(getActivity(), MessageCenterActivity.class);
//                    getActivity().startActivity(intent);
    					IMFactory.openConversation(getActivity());
                } else {
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    getActivity().startActivity(intent);
                }
            }
        });
        adViewPager = (AdViewPager) mContentView.findViewById(R.id.ec_home_ad_viewpager);
        mSearchLayout = mContentView.findViewById(R.id.layout_search);
//        mSearchImage = (ImageView) mContentView.findViewById(R.id.imageview_search);
        mSearchEdit = (TextView) mContentView.findViewById(R.id.tv_search);

        mShangjiLayout = mContentView.findViewById(R.id.layout_shangji);
        mGongyingLayout = mContentView.findViewById(R.id.layout_gongying);
        mCaigouLayout = mContentView.findViewById(R.id.layout_caigou);
        mWuliuLayout = mContentView.findViewById(R.id.layout_wuliu);
        mServiceContactLayout = mContentView.findViewById(R.id.layout_service_contact);
        mShuaihuoLayout = mContentView.findViewById(R.id.layout_shuaihuo);
        
//        mActionGv = (MeasureGridView) mContentView.findViewById(R.id.gv_action_list);
        mSeasonHotGv = (MeasureGridView) mContentView.findViewById(R.id.gv_season_hot);
        mGongyingHotGv = (MeasureGridView) mContentView.findViewById(R.id.gv_gongying_hot);
        scrollView = (ScrollView) mContentView.findViewById(R.id.sv_ec_main);
    }

    private void setUpView() {
    	mShangjiLayout.setOnClickListener(this);
    	mGongyingLayout.setOnClickListener(this);
    	mCaigouLayout.setOnClickListener(this);
    	mWuliuLayout.setOnClickListener(this);
    	mServiceContactLayout.setOnClickListener(this);
    	mShuaihuoLayout.setOnClickListener(this);
    	mSearchLayout.setOnClickListener(this);
    	
    	
		mSeasonHotGv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			    EcHotSell item = (EcHotSell) parent.getItemAtPosition(position);
				Intent intent = new Intent (getActivity(),SeasonHotActivity.class);
				intent.putExtra(ExtraName.isSupply, false);
				intent.putExtra(ExtraName.bigpid, item.getBigpid());
				intent.putExtra(ExtraName.catid, item.getCatid());
				intent.putExtra(ExtraName.title, item.getTitle());
				getActivity().startActivity(intent);
			}
		});
		mGongyingHotGv.setOnItemClickListener(new OnItemClickListener() {
			
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			    EcHotSell item = (EcHotSell) parent.getItemAtPosition(position);
				Intent intent = new Intent (getActivity(),SeasonHotActivity.class);
				intent.putExtra(ExtraName.isSupply, true);
				intent.putExtra(ExtraName.bigpid, item.getBigpid());
                intent.putExtra(ExtraName.catid, item.getCatid());
                intent.putExtra(ExtraName.title, item.getTitle());
				getActivity().startActivity(intent);
			}
		});
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.layout_shangji:
            //目前改为品牌直营
            gotoBrandScopePage();
            break;
        case R.id.layout_gongying:
        	getActivity().startActivity(new Intent(getActivity(),SupplyHallActivity.class));
            MobclickAgent.onEvent(getActivity(), UMengEventID.CLICK_EC_MAIN_SUPPLY_HALL);
        	break;
        case R.id.layout_caigou:
        	getActivity().startActivity(new Intent(getActivity(),PurchaseHallActivity.class));
            MobclickAgent.onEvent(getActivity(), UMengEventID.CLICK_EC_MAIN_PURCHASE_HALL);
        	break;
        case R.id.layout_wuliu:
        	getActivity().startActivity(new Intent(getActivity(),MyLogisticsActivity.class));
        	break;
        case R.id.layout_service_contact:
        	IMFactory.openChatServiceContact(getActivity());
        	break;
        case R.id.layout_shuaihuo:
        	getActivity().startActivity(new Intent(getActivity(),DumpHallActivity.class));
        	break;
        case R.id.layout_search:
            getActivity().startActivity(new Intent(getActivity(),SearchActivity.class));
//            AndroidUtils.sendweixin(getActivity(), "京东方", "的发个梵蒂冈", "http://www.baidu.com");
            break;
        }
        
    }

    /**
     * 进入品牌直营页面
     */
    private void gotoBrandScopePage() {
        //交互逻辑：1、访问用户是否已经授权。是：直接进入直营商品页面； 否：分两种情况，从未申请时，进入提交申请表单页面，如果已经申请，提示正在进行审核。
        //更新用户资料
        AccountManager.updateUserInfo(getContext(), new UserInfoListener() {
            @Override
            public void onUpdateUserInfo(UserInfoEntity userInfoEntity) {
                BrandScope brandScope = userInfoEntity.getData().getBrandScope();
                if (brandScope == null || StringUtil.isEmpty(brandScope.getName())) {
                    getActivity().startActivity(new Intent(getActivity(), BrandScopeApplyActivity.class));
                } else if (brandScope.getAuditStatus() == BrandScopeStatus.IN_AUDITING) {
                    //TODO 弹出审核中提示
                    final MessageDialog dialog = new MessageDialog(getContext());
                    dialog.setMessage("品牌直营准入资料正在审核中，请耐心等待。");
                    dialog.setLeftBtVisible(false);
                    dialog.setOnBtClickListener(new MessageDialog.OnBtClickListener() {
                        @Override
                        public void onLeftBtClick() {

                        }

                        @Override
                        public void onRightBtClick() {
                            dialog.dismiss();
                        }
                    });
                    dialog.show();
                } else if (brandScope.getAuditStatus() == BrandScopeStatus.FAILURE_AUDIT) {
                    //TODO 弹出审核失败提示，可以选择重新审核
                    final MessageDialog dialog = new MessageDialog(getContext());
                    dialog.setMessage("抱歉，品牌直营用户资料，审核未通过！");
                    dialog.setLeftBtText("重新审核");
                    dialog.setRightBtText("取消");
                    dialog.setOnBtClickListener(new MessageDialog.OnBtClickListener() {
                        @Override
                        public void onLeftBtClick() {
                            getActivity().startActivity(new Intent(getActivity(), BrandScopeApplyActivity.class));
                            dialog.dismiss();
                        }

                        @Override
                        public void onRightBtClick() {
                            dialog.dismiss();
                        }
                    });
                    dialog.show();
                } else if (brandScope.getAuditStatus() == BrandScopeStatus.SUCCEED_AUDIT) {
                    getActivity().startActivity(new Intent(getActivity(), BrandScopeActivity.class));
        //        	    getActivity().startActivity(new Intent(getActivity(),BusinessOpportunityActivity.class));
                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("EcMainFragment");
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("EcMainFragment");
    }
}
